package com.hsnn.medstgmini.pro.plan.controller;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.pro.base.model.ViewGoods;
import com.hsnn.medstgmini.pro.base.service.BaseGoodsByHospManager;
import com.hsnn.medstgmini.pro.plan.model.BasePriceadjplan;
import com.hsnn.medstgmini.pro.plan.service.PricePlanManager;
import com.hsnn.medstgmini.pro.plan.service.WsjPriceAdjustManager;
import com.hsnn.medstgmini.pro.project.model.BidProject;
import com.hsnn.medstgmini.pro.project.service.BidProjectManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;

@Controller
@RequestMapping("/pricePlan")
public class PricePlanController {

	private static final Logger log = Logger.getLogger(PricePlanController.class);

	@Autowired
	private PricePlanManager pricePlanManager;
	@Autowired
	private BidProjectManager bidProjectManager;
	@Autowired
	private BaseGoodsByHospManager baseGoodsByHospManager;
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private WsjPriceAdjustManager wsjPriceAdjustManager;

	/**
	 * @category 获取当前登陆人信息
	 * @date 2015年6月14日
	 * @return
	 */
	private SysUser getUser() {
		return (SysUser) session.getAttribute(Constants.USERINFO);
	}

	/**
	 * @category 进入新增调价计划页面
	 * @auth 陈镜宇
	 * @return
	 * @date 2015年6月18日
	 */
	@RequestMapping("/toPricePlanAdd")
	public String toPricePlanAdd() {
		String url = "/pro/plan/pricePlanAdd";
		return url;
	}

	/**
	 * @category 提交调价计划新增
	 * @auth 陈镜宇
	 * @return 计划设置页面
	 * @date 2015年6月15日
	 */
	@RequestMapping("/submitPricePlanAdd")
	@ResponseBody
	public Pagination submitPricePlanAdd() {
		Pagination page = new Pagination();
		String priceAdjPlanName = request.getParameter("priceAdjPlanName");
		String executeCat = request.getParameter("executeCat");
		String executeDatetime = request.getParameter("executeDatetime");
		String remark = request.getParameter("remark");
		String priceAdjAccord = request.getParameter("priceAdjAccord");
		if(StringUtils.isBlank(priceAdjPlanName)){
			page.setSuccess(false);
			page.setMsg("调价计划名称不能为空!");
			return page;
		}
		if(wsjPriceAdjustManager.validateRepeat(priceAdjPlanName.trim(), "")){
			page.setSuccess(false);
			page.setMsg("调价计划名称重复!");
			return page;
		}
		if(StringUtils.isBlank(executeCat)){
			page.setSuccess(false);
			page.setMsg("请选择执行类型!");
			return page;
		}
		if("2".equals(executeCat)){
			if(StringUtils.isBlank(executeDatetime)){
				page.setSuccess(false);
				page.setMsg("请选择执行时间!");
				return page;
			}
			if(DateUtil.parseDateHHTime(executeDatetime).getTime()<new Date().getTime()){
				page.setSuccess(false);
				page.setMsg("执行时间不能小于当前时间!");
				return page;
			}
			page.getConditions().put("executeDatetime", executeDatetime);
		}
		if(StringUtils.isBlank(priceAdjAccord)){
			page.setSuccess(false);
			page.setMsg("调价依据不能为空!");
			return page;
		}
		page.getConditions().put("priceAdjPlanName", priceAdjPlanName.trim());
		page.getConditions().put("executeCat", executeCat);
		page.getConditions().put("priceAdjAccord", priceAdjAccord.trim());
		page.getConditions().put("remark", remark.trim());
		page.getConditions().put("orgId", getUser().getOrgId());
		page.getConditions().put("userId", getUser().getId());
		page.getConditions().put("uuid", UUID.randomUUID().toString());
		try {
			wsjPriceAdjustManager.addPriceAdjPlan(page);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			page.setMsg("数据异常!");
			e.printStackTrace();
		}
		return page;
		
	}

	/**
	 * @category 进入药品调价操作页面
	 * @auth 单大伟
	 * @return 药品调价操作页面
	 * @date 2015年6月15日
	 */
	@RequestMapping("/toPricePlanChange")
	public String toPricePlanChange(Model model, String id) {
		List<BidProject> projList = bidProjectManager.getBidProjectSelectList(null, null);
		model.addAttribute("projList", projList);
		model.addAttribute("pricePlan", pricePlanManager.getPricePlanById(id));
		return "/pro/plan/pricePlanChange";
	}

	/**
	 * @category 弹出添加药品页面
	 * @auth 单大伟
	 * @return 药品调价操作页面
	 * @date 2015年6月15日
	 */
	@RequestMapping("/toPricePlanAddDrug")
	public String toPricePlanAddDrug(Model model, String id) {
		List<BidProject> projList = bidProjectManager.getBidProjectSelectList(null, null);
		model.addAttribute("projList", projList);
		model.addAttribute("pricePlan", pricePlanManager.getPricePlanById(id));
		String url = "/pro/plan/pricePlanAddDrug";
		return url;
	}

	/**
	 * @category 获取未加入调价计划的商品列表json
	 * @auth 单大伟
	 * @return 商品列表json
	 * @date 2015年6月15日
	 */
	@RequestMapping("/getPriceChangeDurgList")
	@ResponseBody
	public Pagination getPriceChangeDurgList() {
		Pagination page = new Pagination(request);
		page.getConditions().put("projName", request.getParameter("projName"));
		page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
		page.getConditions().put("drugName", request.getParameter("drugName"));
		page.getConditions().put("prodComp", request.getParameter("prodComp"));
		page.getConditions().put("drugCode", request.getParameter("drugCode"));
		page.getConditions().put("priceid", request.getParameter("priceid"));
		try {
			baseGoodsByHospManager.getPriceChangeDurgList(page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
		
	}

	/**
	 * 
	 * @category 批量提交调价药品
	 * @auth 单大伟
	 * @return
	 * @date 2015年6月23日
	 */
	@RequestMapping("/batchSubmitDrugTOPlan")
	@ResponseBody
	public Pagination batchSubmitDrugTOPlan() {
		Pagination page = new Pagination();
		String drugs = request.getParameter("drugs");
		String addDatetime = DateUtil.dateTime(new Timestamp(System.currentTimeMillis()));
		try {
			if (drugs != null && !"".equals(drugs)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<Map<String,String>>>() {}.getType();
				List<Map<String,String>> list = gson.fromJson(drugs, type);
				for (Map<String,String> data : list) {
					data.put("addUser", getUser().getId());
					data.put("addDatetime",addDatetime);
					data.put("priceAdjPalnDetailId", UUID.randomUUID().toString());
				}
				page.setOperCount(pricePlanManager.batchSubmitDrugTOPlan(list));
				page.setSuccess(true);
			}
		} catch (JsonSyntaxException e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
		
	}

	/**
	 * @category 获取调价计划明细的商品列表json
	 * @auth 单大伟
	 * @return 商品列表json
	 * @date 2015年6月15日
	 */
	@RequestMapping("/getPriceDurgList")
	@ResponseBody
	public Pagination getPriceDurgList(ViewGoods goods, String priceid) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		Pagination page = new Pagination(request);
		page.getConditions().put("compType", user.getType().toString());
		page.getConditions().put("projName", goods.getProjName());
		page.getConditions().put("goodsCode", goods.getGoodsCode());
		page.getConditions().put("drugName", goods.getDrugName());
		page.getConditions().put("drugComp", goods.getProdComp());
		page.getConditions().put("drugCode", goods.getDrugCode());
		page.getConditions().put("priceid", priceid);
		return pricePlanManager.getPriceDurgList(page);
	}


	/**
	 * @category 批量删除调价明细
	 * @date 2015年7月3日
	 * @param drugs
	 * @return
	 */
	@RequestMapping("/batchDeleteDrug")
	@ResponseBody
	public Pagination batchDeleteDrug() {
		Pagination page = new Pagination();
		String drugs = request.getParameter("drugs");
		try {
			if (drugs != null && !"".equals(drugs)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<String>>() {}.getType();
				List<String> list = gson.fromJson(drugs, type);
				page.setOperCount(pricePlanManager.batchDeleteDrug(list));
				page.setSuccess(true);
			}
		} catch (JsonSyntaxException e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}

	/**
	 * 
	 * @category 批量提交调价药品
	 * @auth 陈镜宇
	 * @return
	 * @date 2015年6月23日
	 */
	@RequestMapping("/batchSubmitPlanDrugEdit")
	@ResponseBody
	public Pagination batchSubmitPlanDrugEdit() {
		Pagination page = new Pagination();
		String drugs = request.getParameter("drugs");
		try {
			if (drugs != null && !"".equals(drugs)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<Map<String,String>>>() {}.getType();
				List<Map<String,String>> list = gson.fromJson(drugs, type);
				page.setOperCount(pricePlanManager.batchSubmitPlanDrugEdit(list));
				page.setSuccess(true);
			}
		} catch (JsonSyntaxException e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
		
	}

	/**
	 * @category 进入未处理调价计划页面
	 * @auth 陈镜宇
	 * @return
	 * @date 2015年6月18日
	 */
	@RequestMapping("/toUnChangePlan")
	public String toUnChangePlan() {
		return "/pro/plan/unChangePlan";
	}

	/**
	 * @category 获取未处理调价计划列表json
	 * @auth 陈镜宇
	 * @return 商品列表json
	 * @date 2015年6月15日
	 */
	@RequestMapping("/getUnChangePlan")
	@ResponseBody
	public Pagination getUnChangePlan(BasePriceadjplan plan) {
		
		Pagination page = new Pagination(request);
		String createStartTime = request.getParameter("createStartTime");
		String createEndTime = request.getParameter("createEndTime");
		String executeStartTime = request.getParameter("executeStartTime");
		String executeEndTime = request.getParameter("executeEndTime");
		page.getConditions().put("createStartTime", createStartTime);
		page.getConditions().put("createEndTime", createEndTime);
		page.getConditions().put("executeStartTime", executeStartTime);
		page.getConditions().put("executeEndTime", executeEndTime);
		page.getConditions().put("executeCat", request.getParameter("executeCat"));
		page.getConditions().put("orgId", getUser().getOrgId());
		try {
			pricePlanManager.getUnChangePlan(page, plan);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			log.error(e.getMessage(),e);
		}
		return page;
	}

	/**
	 * @category 立即执行调价计划
	 * @auth 陈镜宇
	 * @date 2015年6月15日
	 */
	@RequestMapping("/runChangePlan")
	@ResponseBody
	public Pagination runChangePlan(String planId) {
		Pagination page = new Pagination(request);
		page.getConditions().put("planId", planId);
		page.getConditions().put("userId", getUser().getId());
		try {
			pricePlanManager.runChangePlan(page);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			log.error(e.getMessage(),e);
		} catch (Error error) {
			page.setSuccess(false);
			log.error(error.getMessage());
		}
		return page;
	}

	/**
	 * @category 进入编辑调价计划页面
	 * @return
	 * @date 2015年6月18日
	 */
	@RequestMapping("/toPricePlanEdit")
	public String toPricePlanEdit(Model model, String id) {
		Map<String,Object> plan = new HashMap<String,Object>();
		if (StringUtils.isNotBlank(id)) {
			plan = pricePlanManager.getHospplanById(id);
		}
		
		model.addAttribute("plan", plan);
		return "/pro/plan/pricePlanEdit";
	}

	/**
	 * @category 提交编辑调价计划
	 * @return
	 * @date 2015年6月15日
	 */
	@RequestMapping("/submitPricePlanEdit")
	@ResponseBody
	public Pagination submitPricePlanEdit() {
		Pagination page = new Pagination();
		String priceAdjPlanName = request.getParameter("priceAdjPlanName");
		String executeCat = request.getParameter("executeCat");
		String executeDatetime = request.getParameter("executeDatetime");
		String remark = request.getParameter("remark");
		String priceAdjAccord = request.getParameter("priceAdjAccord");
		String priceAdjPlanId = request.getParameter("priceAdjPlanId");
		if(StringUtils.isBlank(priceAdjPlanName)){
			page.setSuccess(false);
			page.setMsg("调价计划名称不能为空!");
			return page;
		}
		if(wsjPriceAdjustManager.validateRepeat(priceAdjPlanName.trim(), priceAdjPlanId)){
			page.setSuccess(false);
			page.setMsg("调价计划名称重复!");
			return page;
		}
		if(StringUtils.isBlank(executeCat)){
			page.setSuccess(false);
			page.setMsg("请选择执行类型!");
			return page;
		}
		if("2".equals(executeCat)){
			if(StringUtils.isBlank(executeDatetime)){
				page.setSuccess(false);
				page.setMsg("请选择执行时间!");
				return page;
			}
			if(DateUtil.parseDateHHTime(executeDatetime).getTime()<new Date().getTime()){
				page.setSuccess(false);
				page.setMsg("执行时间不能小于当前时间!");
				return page;
			}
			page.getConditions().put("executeDatetime", executeDatetime);
		}
		if(StringUtils.isBlank(priceAdjAccord)){
			page.setSuccess(false);
			page.setMsg("调价依据不能为空!");
			return page;
		}
		page.getConditions().put("priceAdjPlanName", priceAdjPlanName.trim());
		page.getConditions().put("executeCat", executeCat);
		page.getConditions().put("priceAdjAccord", priceAdjAccord.trim());
		page.getConditions().put("remark", remark.trim());
		page.getConditions().put("userId", getUser().getId());
		page.getConditions().put("priceAdjPlanId",priceAdjPlanId);
		try {
			wsjPriceAdjustManager.editPriceAdjPlan(page);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			page.setMsg("数据异常!");
			e.printStackTrace();
		}
		return page;
	}

}
